package com.liuweiheng.cloudproviderpayment8002.common.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.liuweiheng.base.enums.UserStatusEnum;
import com.liuweiheng.base.exception.UserException;
import com.liuweiheng.cloudproviderpayment8002.common.dao.UserMapper;
import com.liuweiheng.cloudproviderpayment8002.common.service.UserService;
import com.liuweiheng.cloudproviderpayment8002.entity.Permission;
import com.liuweiheng.cloudproviderpayment8002.entity.Role;
import com.liuweiheng.cloudproviderpayment8002.entity.User;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 服务实现类：用户服务
 *
 * @author lwh
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;


    @Override
    public User selectUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }

    @Transactional
    @Override
    public Integer createUser(User user) {

        if (ObjectUtil.isEmpty(user)) {
            return -1;
        }

        // 检查用户是否存在
        User selUser = this.selectUserByUsername(user.getUsername());

        if (ObjectUtil.isNotNull(selUser)) {
            throw new UserException(selUser.getId(), "用户已存在，请勿重复创建");
        }

        String uuid = StrUtil.uuid();

        String salt = uuid + user.getUsername();

        // 加密
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);

        user.setPassword(md5Hash.toHex());
        user.setSalt(salt);
        user.setState(UserStatusEnum.NOT_ACTIVED.getStatus());

        userMapper.createUser(user);

        // 创建用户
        return user.getId();
    }


    @Override
    public List<Role> selectRoleByUsername(String username) {
        if (StrUtil.isBlank(username)) {
            return null;
        }

        return userMapper.selectAllRoleByUsername(username);
    }


    @Override
    public List<Permission> selectPermByRoleIds(List<Integer> roleIds) {
        if (CollectionUtil.isEmpty(roleIds)) {
            return null;
        }
        return userMapper.selectPermByRoleIds(roleIds);
    }
}
